<template>
  <view class="city-select-page">
    <van-nav-bar
      title="城市选择"
      left-arrow
      @click-left="goBack"
    />
    <van-search v-model:value="searchValue" placeholder="请输入城市名称" />
    <div class="location-section">
      <div class="location-info">
        <van-icon name="location-o" />
        <span @click="getCurrentCity">{{ currentCity }}</span>
        <span class="reposition" @click="reposition">重新定位</span>
      </div>
    </div>
    <div class="hot-cities">
      <!-- 添加点击事件 -->
      <span v-for="hotCity in hotCities" :key="hotCity" class="city-item" @click="selectCity(hotCity)">{{ hotCity }}</span>
    </div>
    <div class="city-list">
      <div v-for="(group, index) in cityGroups" :key="index">
        <div class="group-title">{{ group.title }}</div>
        <div class="group-cities">
          <!-- 添加点击事件 -->
          <span v-for="city in group.cities" :key="city" class="city-item" @click="selectCity(city)">{{ city }}</span>
        </div>
      </div>
    </div>
    <div class="index-bar" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd">
      <span v-for="(letter, index) in indexLetters" :key="index">{{ letter }}</span>
    </div>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useRouter } from 'vue-router';

const router = useRouter();

const searchValue = ref('');
const currentCity = ref('深圳');
const hotCities = ref(['北京', '上海', '广州', '深圳', '杭州']);
const cityGroups = ref([
  {
    title: 'A',
    cities: ['阿坝', '阿克苏', '阿拉尔', '阿拉善', '阿勒泰', '阿里', '鞍山', '安康', '安庆', '安顺', '安阳', '澳门']
  },
  {
    title: 'B',
    cities: ['巴彦淖尔', '巴音郭楞', '巴中', '白城', '白沙', '白山', '白银', '百色', '蚌埠', '包头', '保定', '保山', '保亭', '宝鸡', '北海', '北屯', '本溪', '毕节', '滨州', '博尔塔拉']
  },
  {
        title: 'C',
        cities: ['长春', '重庆', '成都', '长沙', '常熟', '郴州', '常州', '滁州', '巢湖', '池州', '常德', '潮州', '昌吉', '承德', '赤峰']
  },
  {
        title: 'D',
        cities: ['大庆','大连','达州','大港区','当阳','丹东','丹阳','东莞','德阳','丹江口','大理','定西','定州','定兴','大同']
  },
]);
const indexLetters = ref(['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']);
const allCities = ref([
  ...hotCities.value,
  ...cityGroups.value.reduce((acc, group) => acc.concat(group.cities), [])
]);

const goBack = () => {
  router.back();
};

const reposition = () => {
  currentCity.value = '深圳';
};

const handleTouchStart = (e) => {
  // 可以在这里实现触摸索引栏时的交互逻辑，如高亮显示等
};

const handleTouchMove = (e) => {
  // 可以在这里实现触摸移动时的交互逻辑，如滚动到对应字母的城市组
};

const handleTouchEnd = (e) => {
  // 可以在这里实现触摸结束时的交互逻辑
};

watch(searchValue, (newValue) => {
  if (newValue) {
    const filteredCities = allCities.value.filter(city => city.includes(newValue));
    hotCities.value = filteredCities.filter((city, index) => index < 5);
    const newCityGroups = [];
    for (const letter of indexLetters.value) {
      const groupCities = filteredCities.filter(city => city.startsWith(letter));
      if (groupCities.length > 0) {
        newCityGroups.push({
          title: letter,
          cities: groupCities
        });
      }
    }
    cityGroups.value = newCityGroups;
  } else {
    hotCities.value = ['北京', '上海', '广州', '深圳', '杭州'];
    cityGroups.value = [
      {
        title: 'A',
        cities: ['阿坝', '阿克苏', '阿拉尔', '阿拉善', '阿勒泰', '阿里', '鞍山', '安康', '安庆', '安顺', '安阳', '澳门']
      },
      {
        title: 'B',
        cities: ['巴彦淖尔', '巴音郭楞', '巴中', '白城', '白沙', '白山', '白银', '百色', '蚌埠', '包头', '保定', '保山', '保亭', '宝鸡', '北海', '北屯', '本溪', '毕节', '滨州', '博尔塔拉']
      },
      {
        title: 'C',
        cities: ['长春', '重庆', '成都', '长沙', '常熟', '郴州', '常州', '滁州', '巢湖', '池州', '常德', '潮州', '昌吉', '承德', '赤峰']
      },
      {
        title: 'D',
        cities: ['大庆','大连','达州','大港区','当阳','丹东','丹阳','东莞','德阳','丹江口','大理','定西','定州','定兴','大同']
      },
    ];
  }
});

// 新增选择城市方法
const selectCity = (city) => {
  console.log('点击的城市',city);
  router.back({
    
    state: { selectedCity: city }
  });
};



// 新增获取当前城市方法，使用高德地图 API
const getCurrentCity = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(async (position) => {
      const { latitude, longitude } = position.coords;
      try {
        // 使用高德地图逆地理编码 API
        const response = await fetch(`https://restapi.amap.com/v3/geocode/regeo?key=72fee192599504d176a783e7e6eae474&location=${longitude},${latitude}&output=json`);
        const data = await response.json();
        currentCity.value = data.regeocode.formatted_address.match(/.*?市/)?.[0] || '未知城市';
      } catch (error) {
        console.error('获取当前城市失败', error);
      }
    });
  } else {
    console.error('浏览器不支持地理位置服务');
  }
};
</script>

<style scoped>
.city-select-page {
  background-color: #fff;
}

.location-section {
  padding: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.location-info {
  display: flex;
  align-items: center;
}

.reposition {
  color: #ff5000;
  margin-left: auto;
}

.hot-cities {
  padding: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.city-item {
  display: inline-block;
  background-color: #f4f4f4;
  padding: 6px 12px;
  border-radius: 4px;
  margin-right: 10px;
  margin-bottom: 10px;
}

.city-list {
  padding: 0 15px;
}

.group-title {
  font-size: 14px;
  color: #909399;
  margin-top: 15px;
  margin-bottom: 5px;
}

.group-cities {
  display: flex;
  flex-wrap: wrap;
}

.index-bar {
  position: fixed;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
  text-align: center;
}

.index-bar span {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}
</style>